package com.kfm.am.thread;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) throws IOException {
        System.out.println("服务端启动成功,等待连接...");
        ServerSocket serverSocket = new ServerSocket(8888);
        while (true) {
            Socket socket = serverSocket.accept();  // 等待客户端连接 接受连接成功的对象
            System.out.println(socket.getPort() + "连接进来了");
            new SocketThread(socket).start();
        }
    }
}

class SocketThread extends Thread {
    private Socket socket;
    public SocketThread(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        try {
            InputStream stream = socket.getInputStream();
            DataInputStream in = new DataInputStream(stream);
            String msg = in.readUTF();
            InetAddress inetAddress = socket.getInetAddress();
            System.out.println(inetAddress.getHostAddress() + ":" + socket.getPort() + " say " + msg);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }

    }
}
